<?php

namespace model;

use root\base\model;
use common\extend\Check;

class article extends model
{
	//获取栏目数据并分页
	public function jsonPageSelect()
	{
		$db = $this->db();
		//根据标题搜索内容
		if (!empty($_GET['title'])) {
			$where['a.title LIKE'] = '%' . $_GET['title'] . '%';
		}
		//只搜索当前栏目内容
		if (!empty($_GET['cid'])) {
			$where['a.cid'] = intval($_GET['cid']);
		}
		//非超级管理员 只显示自己的内容
		if (sessionInfo('gid') != 1 && !sysrolTF('content_cate_all')) {
			$where['a.uid'] = sessionInfo("userid");
		}
		$p = intval($_GET['page'] ?? 0) ?: 1;
		$num = intval($_GET['limit'] ?? 0) ?: 15;

		$page = ['num' => $num, 'p' => $p, 'return' => true];

		//关联 article_cate  admin_user admin_group 表查询
		$field = 'b.id as cateid , b.name as catename,g.groupname,u.nickname ,a.id,a.cid,a.title,a.imgbl,a.attribute_a,a.attribute_b,a.attribute_c,a.status,a.time';
		$join[] = 'LEFT JOIN article_cate b ON a.cid=b.id';
		$join[] = 'LEFT JOIN admin_user u ON a.uid=u.id';
		$join[] = 'LEFT JOIN admin_group g ON u.gid=g.id';
		$result['data'] = $db->table('article a')->field($field)->where($where)->join($join)->Page($page)->order('a.id DESC')->select();
		$result['page'] = $db->getPage();

		return $result;
	}


	//信息统计查询
	public static function findCount()
	{
		$data = [];
		$pdo = \z\pdo::Init();
		$prefix = $pdo->GetConfig();
		$fix = $prefix['prefix'];

		//每月全量分析统计
		$pdo->Cache(86000);
		$data['meiyue'] = $pdo->QueryAll("SELECT COUNT(1) AS total, MONTH(`time`) AS months FROM {$fix}article GROUP BY months asc;");
		$pdo->Cache(86000);
		$data['meiyueBJ'] = $pdo->QueryAll("SELECT COUNT(1) AS total, MONTH(`time`) AS months FROM {$fix}article WHERE status=1 GROUP BY months asc;");
		//每周全量分析统计
		$pdo->Cache(86000);
		$data['meizhou'] = $pdo->QueryAll("SELECT COUNT(1) AS total, WEEK(`time`) AS weeks FROM {$fix}article  GROUP BY weeks asc;");
		$pdo->Cache(86000);
		$data['meizhouBJ'] = $pdo->QueryAll("SELECT COUNT(1) AS total, WEEK(`time`) AS weeks FROM {$fix}article  WHERE status=1 GROUP BY weeks asc;");
		//每年全量分析统计
		$pdo->Cache(86000);
		$data['meinian'] = $pdo->QueryAll("SELECT COUNT(1) AS total, YEAR(`time`) AS years FROM {$fix}article  GROUP BY years asc;");
		$pdo->Cache(86000);
		$data['meinianBJ'] = $pdo->QueryAll("SELECT COUNT(1) AS total, YEAR(`time`) AS years FROM {$fix}article  WHERE status=1 GROUP BY years asc;");
		//每年按栏目分析统计
		$pdo->Cache(86000);
		$data['catenian'] = $pdo->QueryAll("SELECT COUNT(1) AS total, a.cid AS cids,b.name AS catename,b.color FROM {$fix}article a inner JOIN {$fix}article_cate b ON b.id=a.cid and b.ct=1 WHERE DATE_FORMAT(a.time,'%Y') = DATE_FORMAT(NOW(),'%Y') GROUP BY cids asc");
		//每月按栏目分析统计
		$pdo->Cache(86000);
		$data['cateyue'] = $pdo->QueryAll("SELECT COUNT(1) AS total, a.cid AS cids,b.name AS catename,b.color FROM {$fix}article a inner JOIN {$fix}article_cate b ON b.id=a.cid and b.ct=1 WHERE DATE_FORMAT(a.time,'%Y-%m') = DATE_FORMAT(NOW(),'%Y-%m') GROUP BY cids asc");
		return $data;
	}

	//关联查找一条数据
	public function findData()
	{
		$db = $this->db();
		$where['a.id'] = $_GET['id'];
		$join[] = 'LEFT JOIN article_content b ON a.id=b.aid';
		$result['content'] = $db->table('article a')->Join($join)->where($where)->find();

		//附件信息
		$attmentId = $result['content']['attid'];
		if (!empty($attmentId)) {
			$wheresAtt = "attid IN (" . $attmentId . ")";
			$result['attments'] = $db->table('attments')->where($wheresAtt)->Select();
		}

		return $result;
	}

	//添加数据
	public function insertData()
	{
		//插入数据信息部分
		$db = $this->db('article');
		$attid = empty($_POST['attid']) ? null : $_POST['attid'];
		$data = [
			'cid' => $_POST['cid'],
			'title' => varFilter($_POST['title']),
			'attid' => $attid,
			'attribute_a' => $_POST['attribute_a'],
			'attribute_b' => $_POST['attribute_b'],
			'attribute_c' => $_POST['attribute_c'],
			'examine' => varFilter($_POST['examine']),
			'img' => $_POST['img'],
			'imgbl' => empty($_POST['img']) ? 0 : 1,
			'time' => date('Y-m-d H:i:s', time()),
			'status' => $_POST['status'],
			'uid' => sessionInfo("userid"),
			'gid' => sessionInfo("gid"),
		];
		//验证数据
		$msg = Check::rule(
			array(check::len($data['mast']), '标题必须为3-200个字，请检查'),
			array(check::len($data['title'], 6, 400), '标题必须为3-200个字，请检查'),
			array(check::isChinese($data['examine']), '审核人必须为中文，请检查'),
			array(check::isImg($data['img']), '缩略图必须为有效图片路径，请检查')
		);
		if ($msg !== true)
			return  ['status' => 0, 'msg' => $msg];

		$re_key = $db->insert($data); //$this->error($db->getError());

		//根据主键插入内容部分
		if (!empty($_POST['content'])) {
			$db_content = $this->db('article_content');
			$data_content = [
				'content' => $_POST['content'],
				'aid' => $re_key,
			];
			$result_content = $db_content->insert($data_content);
		}

		if ($re_key > 0 || $result_content != 0) {
			insertSqlLog("添加内容信息ID：" . $re_key); //写入日志
			return ['key' => $re_key, 'status' => 1, 'msg' => '添加成功', 'cid' => $_POST['cid']];
		} else {
			return ['status' => 0, 'msg' => '数据错误！添加失败'];
		}
	}
	//关联更新数据
	public function updateData()
	{
		$db = $this->db();
		$where['id'] = $_POST['id'];
		$attid = empty($_POST['attid']) ? null : $_POST['attid'];
		$data = [
			'cid' => $_POST['cid'],
			'title' => varFilter($_POST['title']),
			'attid' => $attid,
			'attribute_a' => $_POST['attribute_a'],
			'attribute_b' => $_POST['attribute_b'],
			'attribute_c' => $_POST['attribute_c'],
			'examine' => varFilter($_POST['examine']),
			'img' => $_POST['img'],
			'imgbl' => empty($_POST['img']) ? 0 : 1,
			//'time' => date('Y-m-d H:i:s', time()),
			'status' => $_POST['status'],
		];
		//验证数据
		$msg = Check::rule(
			array(check::len($_POST['mast']), '标题必须为3-200个字，请检查'),
			array(check::len($_POST['title'], 6, 400), '标题必须为3-200个字，请检查'),
			array(check::isChinese($_POST['examine']), '审核人必须为中文，请检查'),
			array(check::isImg($_POST['img']), '缩略图必须为有效图片路径，请检查')
		);
		if ($msg !== true)
			return ['status' => 0, 'msg' => $msg];

		$re_key = $db->table('article')->Where($where)->Update($data); //$this->error($db->getError());

		//存在修改，不存在插入
		if (!empty($_POST['content'])) {
			$db_content = $this->db('article_content');
			$data_content = [
				'content' => $_POST['content'],
				'aid' => $_POST['id'],
			];
			$result_content = $db_content->IfUpdate($data_content);
		}

		if ($re_key > 0 || $result_content != 0) {
			insertSqlLog("修改内容信息ID：" . $_POST['id']); //写入日志
			return ['key' => $re_key, 'status' => 1, 'msg' => '修改成功', 'cid' => $_POST['cid']];
		} else {
			return ['status' => 0, 'msg' => '数据没有变化！'];
		}
	}

	//关联删除一条数据
	public function deleteOneData()
	{
		$pdo = \z\pdo::Init();
		//获取PDO设置
		$prefix = $pdo->GetConfig();
		$fix = $prefix['prefix'];
		//关联删除
		$sql = "DELETE {$fix}article,{$fix}article_content from {$fix}article LEFT JOIN {$fix}article_content ON {$fix}article.id={$fix}article_content.aid WHERE {$fix}article.id=:id";
		$bind = [':id' => $_POST['id']];
		$pdo->Prepare($sql);    //返回预处理的句柄

		insertSqlLog("删除内容信息ID：" . $_POST['id']); //写入日志
		return $pdo->Query($sql, $bind);
	}

	//审核一条数据
	public function switchStatus()
	{
		$db = $this->db();
		$where['id'] = $_POST['id'];
		$data = [
			'status' => $_POST['status']
		];
		insertSqlLog("切换内容信息状态ID：" . $_POST['id']); //写入日志

		return $db->table('article')->where($where)->Update($data);
	}

	
}
